package com.example.demo.grbkxt.dao;

import com.example.demo.grbkxt.model.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private static final String DATA_DIR = System.getProperty("user.dir") + File.separator + "data";
    private static final String DATA_FILE = DATA_DIR + File.separator + "users.json";
    private static final Gson gson = new Gson();

    public UserDao() {
        File dir = new File(DATA_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 如果用户文件不存在，创建默认管理员账户
        File file = new File(DATA_FILE);
        if (!file.exists()) {
            List<User> defaultUsers = new ArrayList<>();
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword("admin123");
            admin.setAdmin(true);
            defaultUsers.add(admin);
            saveUsers(defaultUsers);
        }
    }

    public List<User> getAllUsers() {
        try (Reader reader = new FileReader(DATA_FILE)) {
            Type type = new TypeToken<List<User>>() {
            }.getType();
            return gson.fromJson(reader, type);
        } catch (IOException e) {
            return new ArrayList<>();
        }
    }

    public void saveUsers(List<User> users) {
        try (Writer writer = new FileWriter(DATA_FILE)) {
            gson.toJson(users, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addUser(User user) {
        List<User> users = getAllUsers();
        users.add(user);
        saveUsers(users);
    }

    public void deleteUser(String username) {
        List<User> users = getAllUsers();
        users.removeIf(user -> user.getUsername().equals(username));
        saveUsers(users);
    }

    public User getUserByUsername(String username) {
        return getAllUsers().stream()
                .filter(user -> user.getUsername().equals(username))
                .findFirst()
                .orElse(null);
    }

    public void updateUser(User updatedUser) {
        List<User> users = getAllUsers();
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getUsername().equals(updatedUser.getUsername())) {
                users.set(i, updatedUser);
                break;
            }
        }
        saveUsers(users);
    }
}
